<?php

include 'EncrypterContract.php';
class Encrypter implements EncrypterContract
{
    const KEY='EgYKEZ2jX0SwAPGQSAz/QkStNhcRkjfrwtbQGZI3bhs=';//定义加密秘钥
    const CIPHER='AES-256-CBC';//加密方式

    protected $key;//秘钥
    protected $cipher;//加密标准

    /**
     * @param  string  $key
     * @param  string  $cipher
     * @return void
     */
    public function __construct()
    {
        $this->key=base64_decode(self::KEY);
        $this->cipher=self::CIPHER;

        if(!static::supported($this->key, $this->cipher)){
            throw new Exception('只支持AES-128-CBC 和 AES-256-CBC 加密方式');
        }

    }

    /**
     * 确定给定的密钥和加密标准是否匹配。
     *
     * @param  string  $key
     * @param  string  $cipher
     * @return bool
     */
    public static function supported($key, $cipher)
    {
        $length = mb_strlen($key, '8bit');
        return ($cipher === 'AES-128-CBC' && $length === 16) ||
            ($cipher === 'AES-256-CBC' && $length === 32);
    }

    /**
     * 为给定的加密标准新生成一个key
     *
     * @param  string  $cipher
     * @return string
     */
    public static function generateKey($cipher)
    {
        $randStr=random_bytes($cipher == 'AES-128-CBC' ? 16 : 32);
        return base64_encode($randStr);
    }

    /**
     * 加密，可加密数组和字符串
     *
     * @param  mixed  $value
     * @param  bool  $serialize
     * @return string
     *
     */
    public function encrypt($value, $serialize = true)
    {
        $iv = static::randomBytes(openssl_cipher_iv_length($this->cipher));

        // First we will encrypt the value using OpenSSL. After this is encrypted we
        // will proceed to calculating a MAC for the encrypted value so that this
        // value can be verified later as not having been changed by the users.
        $value = \openssl_encrypt(
            $serialize ? serialize($value) : $value,
            $this->cipher, $this->key, 0, $iv
        );

        if ($value === false) {
            throw new Exception('Could not encrypt the data.');
        }

        // Once we get the encrypted value we'll go ahead and base64_encode the input
        // vector and create the MAC for the encrypted value so we can then verify
        // its authenticity. Then, we'll JSON the data into the "payload" array.
        $mac = $this->hash($iv = base64_encode($iv), $value);

        $json = json_encode(compact('iv', 'value', 'mac'));

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('Could not encrypt the data.');
        }

        return base64_encode($json);
    }


    /**
     * Decrypt the given value.
     *
     * @param  mixed  $payload
     * @param  bool  $unserialize
     * @return string
     *
     * @throws \Illuminate\Contracts\Encryption\DecryptException
     */
    public function decrypt($payload, $unserialize = true)
    {
        $payload = $this->getJsonPayload($payload);

        $iv = base64_decode($payload['iv']);

        // Here we will decrypt the value. If we are able to successfully decrypt it
        // we will then unserialize it and return it out to the caller. If we are
        // unable to decrypt this value we will throw out an exception message.
        $decrypted = \openssl_decrypt(
            $payload['value'], $this->cipher, $this->key, 0, $iv
        );

        if ($decrypted === false) {
            throw new Exception('Could not decrypt the data.');
        }

        return $unserialize ? unserialize($decrypted) : $decrypted;
    }


    /**
     * Create a MAC for the given value.
     *
     * @param  string  $iv
     * @param  mixed  $value
     * @return string
     */
    protected function hash($iv, $value)
    {
        return hash_hmac('sha256', $iv.$value, $this->key);
    }

    /**
     * Get the JSON array from the given payload.
     *
     * @param  string  $payload
     * @return array
     *
     * @throws \Illuminate\Contracts\Encryption\DecryptException
     */
    protected function getJsonPayload($payload)
    {
        $payload = json_decode(base64_decode($payload), true);

        // If the payload is not valid JSON or does not have the proper keys set we will
        // assume it is invalid and bail out of the routine since we will not be able
        // to decrypt the given value. We'll also check the MAC for this encryption.
        if (! $this->validPayload($payload)) {
            throw new Exception('The payload is invalid.');
        }

        if (! $this->validMac($payload)) {
            throw new Exception('The MAC is invalid.');
        }

        return $payload;
    }

    /**
     * Verify that the encryption payload is valid.
     *
     * @param  mixed  $payload
     * @return bool
     */
    protected function validPayload($payload)
    {
        return is_array($payload) && isset(
                $payload['iv'], $payload['value'], $payload['mac']
            );
    }

    /**
     * Determine if the MAC for the given payload is valid.
     *
     * @param  array  $payload
     * @return bool
     */
    protected function validMac(array $payload)
    {
        $calculated = $this->calculateMac($payload, $bytes = static::randomBytes(16));

        return hash_equals(
            hash_hmac('sha256', $payload['mac'], $bytes, true), $calculated
        );
    }

    /**
     * Calculate the hash of the given payload.
     *
     * @param  array  $payload
     * @param  string  $bytes
     * @return string
     */
    protected function calculateMac($payload, $bytes)
    {
        return hash_hmac(
            'sha256', $this->hash($payload['iv'], $payload['value']), $bytes, true
        );
    }


    /**
     * 生成随机字符串
     * @param int $length
     * @return string
     */
    protected static function randomBytes($length =16)
    {
        $randStr = '';
        for ($i = 0; $i < $length; $i++)
        {
            $randStr .= chr(mt_rand(33, 126));
        }
        return $randStr;
    }
}
